/*
    Created by Nic wu
**/
public with sharing class SelectAvailableCity
{
    public Integer AvaCityNum{get;set;}
    public String AvaCityId{get;set;}
    public String selCityName{get;set;}
    public boolean isRendered{get;set;}
    public String msg1 { get; set;}
    public String msg { get; set; }
    
    public  List<Place__c> al = new List<Place__c>();
    public User Usr{get;set;}
    public id UsrID{get;set;}
    public String UrlId{get;set;}
    public List<String> SubSalesCites {get;set;}
    public List<User> UsrList = new List<User>(); 
    public List<RollingForecast__c> rList {get;set;}
    public boolean MsgShow{get;set;}
    public String ErrMsg{get;set;}
    public String ErrDetail{get;set;}
    public String MsgType{get;set;}
    public List<String> recList{get;set;}
    public boolean isBlock{get;set;}
    
    //constructor
    public SelectAvailableCity(ApexPages.StandardController controller) {
    
         UsrID =UserInfo.getUserId();
         Usr = [select id, name, email, UserRegion__c,ProfileId, UserSubRegion__c from User where id =: UsrID limit 1];
         UrlId = System.currentPageReference().getParameters().get('id');
         UsrList = [select id,isCityManager__c, name,  ForcastCity__c from User where id =:UsrID and isCityManager__c =: true];
         Profile pp  = [select id from profile where name = 'System Administrator'or name =: '系统管理员'];
         Place__c p = new Place__c();
         if(Usr.ProfileId == pp.id)         {
             //p = [select id from Place__c where PlaceType__c=:'Region'];
             al = [select id, Name from Place__c where PlaceType__c = 'City' order by Region__c, Subregion__c asc];
         }
         else{
             p = [select id from Place__c where PlaceType__c=:'Region' and name =: Usr.UserRegion__c];
              al = [select id, Name from Place__c where PlaceType__c = 'City' and Region__c=:p.id  order by Region__c, Subregion__c asc];
         }
        
        // al = [select id, name from User where id =: UserInfo.getUserId()];
         
          
          List<User> u = [select id,isCityManager__c, name,  ForcastCity__c from User where id =:UsrID and (isCityManager__c =: true or  ProfileId =: pp.id)];          
          
          if(u[0].isCityManager__c)
          {
              List<String> spl = u[0].ForcastCity__c .split(';');
              List<Place__C > pList = [Select id,Name From Place__C Where name in:spl];
              if(pList.size() > 0)
              {
                  AvaCityNum=0;
                  AvaCityOptions.add(new SelectOption('-1','无'));
                  for(Integer i=0;i<pList.size();i++) {
                        if(pList[i]!=null) {
                        AvaCityNum+=1;
                        AvaCityOptions.add(new SelectOption(string.valueof(i),pList[i].Name));
                        }
                    }
                 rList = [select id, name, ForecastCity__c from RollingForecast__c where year__c=: String.valueOf(Date.today().year()) and month__c =:String.valueOf(Date.today().month()) and ownerId =: UserInfo.getUserId()];
                 setDefault();   
                 al.clear();
                 al = pList ; 
              }
          }
          else
          {
          AvaCityNum=0;
          AvaCityOptions.add(new SelectOption('-1','无'));
          for(Integer i=0;i<al.size();i++) {
                if(al[i]!=null) {
                AvaCityNum+=1;
                AvaCityOptions.add(new SelectOption(string.valueof(i),al[i].Name));
                }
            }
         
         rList = [select id, name, ForecastCity__c from RollingForecast__c where year__c=: String.valueOf(Date.today().year()) and month__c =:String.valueOf(Date.today().month()) and ownerId =: UserInfo.getUserId()];
         setDefault();
         }
    }
    
    public void initialize() { 
         isRendered = true;
         //判断是否 城市经理
         List<User> l = [select id, name, isCityManager__c from User where id =: UserInfo.getUserId() limit 1];
        list<Profile> pl = [select id, name from Profile where id =: UserInfo.getProfileId() and name =: '系统管理员'];
        isBlock=true;
    }
    
    public List<CityBudget__c> CityBudgetRate{
        get{
            if(CityBudgetRate==null)
                CityBudgetRate = new List<CityBudget__c>();
            return CityBudgetRate;
        }
        set;
    }
    
    //for error msg
    public  boolean isR {
        get{
        if(isRendered)
            return false;
        else
            return true;
        }
        set;
    }
    
    // initialize render type
    public void initRender(){
        
            if(UsrList.size()>0){
                isRendered =false;
            }
            else {
                errMsg ='错误';
                isRendered =true;
            }
    }
    
    //获取这个用户所管辖城市的list
    public List<SelectOption> AvaCityOptions{ 
        get{
            if(AvaCityOptions == null)
                AvaCityOptions = new List<SelectOption>();
                
            return AvaCityOptions ;
        }
        set; 
    }

    public PageReference Cancel() {
        pageReference pr = new pageReference('/a1q/o');    
        pr.setredirect(true);
        return pr;
    }
    
    public void setDefault(){
        MsgShow =false;
        ErrMsg ='';
        MsgType ='';
        ErrDetail='';
        isRendered = true;
    }
    
    public PageReference actionSupport(){
        
        setDefault();
        if(AvaCityNum==-1){
            MsgShow =true;
            ErrMsg ='空白项不能进入预测!';
            MsgType ='WARNING';
            isRendered = true;
            return null;
        }else{
            isRendered = false;
        }
        
        recList = new List<String>();
        
        selCityName =(String)al[AvaCityNum].get('Name');
        
        
        if(rList!=null && rList.size()>0){
            for(Integer i=0;i<rList.size();i++){
                if(rList[i].ForecastCity__c == selCityName){
                    recList.add(rList[i].name);
                }
            }
        } 
        
        if(recList.size()<1){
            recList.add('无');
        }
        return null;
    }
    
    public PageReference Enter() {
        
        if(al.size()<1){
            return null;
        }
        if(AvaCityNum==-1){
            ErrMsg ='空白项, 不能进入预测, 请重新选择.';
            MsgShow =true;
            MsgType ='ERROR';
            isRendered = true;
            return null;
        }
        selCityName =(String)al[AvaCityNum].get('Name');
        
        AvaCityId = [select id from Place__c where placeType__c=:'City' and name =: selCityName limit 1][0].id;
        
        CityBudgetRate = [Select Id, Name, Month__c, City__c, Rate__c From CityBudget__c where Place__c=: AvaCityId limit 1];
        
        List<RollingForecast__c> l = [select id, name, Apply_date__c, year__c, month__c from RollingForecast__c 
                                                    where ownerId =: UserInfo.getUserId() and Sales_City__c =: AvaCityId and year__c=:String.valueOf(Date.today().year()) and month__c =: String.valueOf(Date.today().month()) ];
        
        //如果 rolling forecast 在 选择的城市 的record 存在的话, 则转到那个那条record
        if(l.size()>0) {
                PageReference forePage = new PageReference('/apex/ForecastPage' + '?rid=' + String.valueOf(l[0].id) +'?CityId='+AvaCityId);
                forePage.setRedirect(true);
                return forePage;
        }
        //如果 rolling forecast 在选择的城市中, 没有record的话, 则新建一条record, 获取rid 转到 那条record
        else{
                RollingForecast__c r = new RollingForecast__c();
                r.Name = selCityName+'_'+Date.today().year()+'年'+'_'+Date.today().month()+'月'+'_'+UserInfo.getName();
                r.Sales_City__c = AvaCityId;
                r.UserEmail__c = Usr.email;
                r.ForecastCity__c =selCityName;
                
                if(CityBudgetRate.size()>0){
                    r.Rate__c = CityBudgetRate[0].Rate__c;
                }else{
                    r.Rate__c = 0;
                }
                // 赋值给 uniqueid with year + month + cmID
                String sUID =String.valueOf(UsrID);
                Integer len = sUID.length()-3;
                String s = sUID.substring(0, len);
                r.UniqueId__c =String.valueOf(Date.today().year())+String.valueOf(Date.today().month())+s+AvaCityId;
                r.Apply_Date__c = Date.today();
                insert r;
                PageReference forePage = new PageReference('/apex/ForecastPage'+ '?rid=' + String.valueOf(r.id) +'?CityId='+AvaCityId);
                //system.assert(false, String.valueOf(forePage));
                //r.ApproveUrl__c = String.valueOf(forePage);
                //update r;
                forePage.setRedirect(true);
                return forePage;
        }
    }
}